package mj.scott.back.base.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import mj.scott.back.test.pojo.vo.OptionVO;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import java.sql.*;
import java.util.List;

/**
 * 自定义类型处理器，专门处理数据库JSON字符串到List<OptionVO>的转换
 */
@MappedTypes({List.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class OptionListTypeHandler extends BaseTypeHandler<List<OptionVO>> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<OptionVO> parameter, JdbcType jdbcType) throws SQLException {
        try {
            String jsonString = objectMapper.writeValueAsString(parameter);
            ps.setString(i, jsonString);
        } catch (Exception e) {
            throw new SQLException("Error converting List<OptionVO> to JSON string", e);
        }
    }

    @Override
    public List<OptionVO> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String jsonString = rs.getString(columnName);
        return parseJsonToList(jsonString);
    }

    @Override
    public List<OptionVO> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String jsonString = rs.getString(columnIndex);
        return parseJsonToList(jsonString);
    }

    @Override
    public List<OptionVO> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String jsonString = cs.getString(columnIndex);
        return parseJsonToList(jsonString);
    }

    private List<OptionVO> parseJsonToList(String jsonString) throws SQLException {
        if (jsonString == null || jsonString.isEmpty()) {
            return null;
        }
        try {
            return objectMapper.readValue(jsonString,
                objectMapper.getTypeFactory().constructCollectionType(List.class, OptionVO.class));
        } catch (Exception e) {
            throw new SQLException("Error parsing JSON string to List<OptionVO>", e);
        }
    }
}
